package cn.nfwx.tv.widget.nfwxplayer;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.nfwx.tv.R;
import cn.nfwx.tv.controller.player.BasePlayerController;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.widget.seekbar.Point;
import cn.nfwx.tv.widget.seekbar.PointSeekBar;

public class NfwxButtonView extends LinearLayout {
    private SimpleDateFormat _sf;
    private SimpleDateFormat dateFormat;

    ImageView iv_player_btn, player_size_change;
    TextView tv_player_time, tv_player_maxtime, btn_tvprogram;
    PointSeekBar sb_player;
    INfwxVideoPlayer mVideoPlayer;
    BasePlayerController mVideoPlayerController;

    OnNfwxButtonViewListenter onNfwxButtonViewListenter;

    int seekPosition; // 点播移时

    boolean _seeking = false;

    final static int live_seek_max = 2 * 60 * 60; // 最大直播时移时长
    long liveTime;
    long liveSeekTime;

    private long clipTimeCode;

    private long perTime;

    private List<TvProgram> mTodayPrograms = new ArrayList<>();
    private boolean _hasProgramloaded;
    private boolean _isSeekEnable;

    private boolean isSeeking = false;
    private static final int TIME_COUNT = 8;
    private static final int NET_TIME_COUNT = 10;
    private int time = TIME_COUNT;
    private int netTime = NET_TIME_COUNT;

    public void setOnNfwxButtonViewListenter(OnNfwxButtonViewListenter onNfwxButtonViewListenter) {
        this.onNfwxButtonViewListenter = onNfwxButtonViewListenter;
    }

    public NfwxButtonView(Context context) {
        this(context, null);
    }

    public NfwxButtonView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NfwxButtonView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context);
    }

    private void init(Context context) {
        if (_sf == null) {
            _sf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        }
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        }

        LayoutInflater.from(context).inflate(R.layout.layout_player_controller, this, true);
        iv_player_btn = findViewById(R.id.iv_player_btn);
        player_size_change = findViewById(R.id.player_size_change);
        tv_player_time = findViewById(R.id.tv_player_time);
        tv_player_maxtime = findViewById(R.id.tv_player_maxtime);
        sb_player = findViewById(R.id.sb_player);
        btn_tvprogram = findViewById(R.id.btn_tvprogram);

        sb_player.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) { // 是否人为操作
                    return;
                }
                if (_seeking) {
                    if (mVideoPlayerController.isLive()) {
                        int len = live_seek_max - progress;
                        liveSeekTime = liveTime - len;
                        tv_player_time.setText(TimeUtil.getFormatHHmmssDate((int) liveSeekTime));
                    } else {
                        seekPosition = progress;
                        tv_player_time.setText(TimeUtil.toTime(progress));
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (onNfwxButtonViewListenter != null) {
                    onNfwxButtonViewListenter.onStartTrackingTouch();
                }
                _seeking = true;
                if (mVideoPlayerController.isLive()) {
                    hiddenBubble();
                    liveTime = mVideoPlayer.getTimeCode() + (live_seek_max - seekBar.getProgress());
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (onNfwxButtonViewListenter != null) {
                    onNfwxButtonViewListenter.onStopTrackingTouch();
                }
                if (_seeking) {
                    _seeking = false;
                    if (mVideoPlayerController.isLive()) {
                        isSeeking = false;
                        if (liveSeekTime >= liveTime) {
                            mVideoPlayerController.setShift(false);
                            mVideoPlayerController.reStart();
                            sb_player.setEnabled(false);
                        } else {
                            sb_player.setEnabled(false);
                            mVideoPlayer.seekByTimeCode(liveSeekTime);
                        }
                    } else {
                        isSeeking = true;
                        if (seekPosition <= 0) {
                            sb_player.setEnabled(false);
                            mVideoPlayer.seekTo(0);
                        } else {
                            sb_player.setEnabled(false);
                            mVideoPlayer.seekTo(seekPosition);
                        }
                    }
                }
            }
        });

        sb_player.setPointSeekBarListener(new PointSeekBar.PointSeekBarListener() {
            @Override
            public void seekToPoint(Point point) {
                _seeking = false;
                // 返回到对应的时间轴
                //_player.setOnSeekCompleteListener(PlayerViewController.getInstance());
                if (mVideoPlayerController.isLive()) {
                    hiddenBubble();
                    final long p = (mVideoPlayer.getTimeCode() + (live_seek_max - sb_player.getProgress())) - point.getTime();
                    mVideoPlayer.seekByTimeCode(point.getTime());
                    sb_player.setProgress((int) (live_seek_max - p));
                }
            }
        });
    }

    public void setClickListener(OnClickListener clickListener) {
        btn_tvprogram.setOnClickListener(clickListener);
        iv_player_btn.setOnClickListener(clickListener);
        player_size_change.setOnClickListener(clickListener);
        setOnClickListener(clickListener);
    }

    public void attach(INfwxVideoPlayer ijkVideoView) {
        mVideoPlayer = ijkVideoView;
    }

    public void attachController(BasePlayerController videoPlayerController) {
        mVideoPlayerController = videoPlayerController;
    }

    /**
     * 暂停按钮
     */
    public void stopView() {
        iv_player_btn.setSelected(true);
    }

    /**
     * 播放按钮
     */
    public void playView() {
        iv_player_btn.setSelected(false);
    }

    boolean _isInit = false;
    boolean _isShow = false;

    public void updatePosiont() {
        if (!_seeking) {
            tv_player_maxtime.setText(TimeUtil.toTime((int) mVideoPlayer.getDuration()));
            if (mVideoPlayerController.isLive()) {
                if (mVideoPlayer.getTimeCode() > 0) {
                    refreshSeekBar();
                    loadProgramSeek();
                    long time = mVideoPlayer.getTimeCode();
                    tv_player_time.setText(TimeUtil.getFormatHHmmssDate((int) time));
                    sb_player.setEnabled(true);
                } else {
                    tv_player_time.setText("00:00:00");
                }
            } else {
                refreshSeekBar();
                sb_player.setEnabled(true);
                sb_player.setMax((int) mVideoPlayer.getDuration());
                sb_player.setProgress((int) mVideoPlayer.getCurrentPosition());
                tv_player_time.setText(TimeUtil.toTime((int) mVideoPlayer.getCurrentPosition()));
                if (!mVideoPlayerController.isLive() && TimeUtil.toTime((int) mVideoPlayer.getDuration()).equals(TimeUtil.toTime((int) mVideoPlayer.getCurrentPosition())) && mVideoPlayer.getDuration() != 0) {
                    if (onNfwxButtonViewListenter != null) {
                        onNfwxButtonViewListenter.playEnd();
                    }
                }
            }
            if (perTime >= mVideoPlayer.getTimeCode()) {
                if (!_isInit) {
                    if (_isShow) {
                        mVideoPlayerController.showLoading();
                    } else {
                        _isShow = true;
                    }
                    if (perTime != 0) {
                        if (time-- <= 0) {
                            if (mVideoPlayer.isPlaying() || mVideoPlayer.isBufferingPaused() || mVideoPlayer.isBufferingPlaying() || (mVideoPlayerController.isLive() && mVideoPlayer.isCompleted())) {
                                if (!isSeeking) {
                                    mVideoPlayerController.reStart();
                                }
                                if (netTime-- < 0) { // 弹出网络提示
                                    mVideoPlayerController.showNet();
                                    netTime = NET_TIME_COUNT;
                                }
                            }
                            time = TIME_COUNT;
                        }
                    }
                } else {
                    _isInit = false;
                }
                perTime = mVideoPlayer.getTimeCode();
            } else {
                if (perTime == 0) {
                    mVideoPlayerController.showLoading();
                    _isInit = true;
                }
                time = TIME_COUNT;
                netTime = NET_TIME_COUNT;
                _isShow = false;
                isSeeking = false;
                mVideoPlayerController.hideLoading();
                perTime = mVideoPlayer.getTimeCode();
            }
        }
    }

    public void reset() {
        sb_player.setProgress(0);
        tv_player_time.setText(TimeUtil.toTime(0));
        sb_player.setEnabled(false);
        iv_player_btn.setClickable(false);
        perTime = 0;
        time = TIME_COUNT;
        netTime = TIME_COUNT;
        _isShow = false;
        isSeeking = false;
    }

    public void setProgress(int progress) {
        sb_player.setProgress(progress);
        tv_player_time.setText(TimeUtil.toTime(0));
        sb_player.setEnabled(false);
    }

    public void refreshView() {
        tv_player_maxtime.setVisibility(mVideoPlayerController.isLive() ? GONE : VISIBLE);
        sb_player.setMax(live_seek_max);
        sb_player.setProgress(mVideoPlayerController.isLive() ? live_seek_max : 0);
        perTime = 0;
        iv_player_btn.setClickable(true);
        if (mVideoPlayerController.isLive()) {
            btn_tvprogram.setText("回看");
        } else {
            btn_tvprogram.setText("列表");
        }
    }

    public void hideTvprogram() {
        btn_tvprogram.setVisibility(GONE);
    }

    public void showTvprogram() {
        btn_tvprogram.setVisibility(VISIBLE);
    }

    /**
     * 剪切暂停记录对应的位置
     */
    public void clipPause() {
        if (mVideoPlayer != null) {
            if (sb_player.getProgress() < live_seek_max) {
                clipTimeCode = mVideoPlayer.getTimeCode();
            } else {
                clipTimeCode = -1;
            }
            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
        } else {
            clipTimeCode = -1;
        }
    }

    /**
     * 回复
     */
    public void clipResume() {
        if (mVideoPlayer != null) {
            if (clipTimeCode == -1) {
                mVideoPlayerController.reStart();
            } else {
                if (sb_player.getProgress() < live_seek_max) {
                    mVideoPlayer.seekByTimeCode(clipTimeCode);
                } else {
                    mVideoPlayerController.reStart();
                }
            }
        }
    }

    /**
     * 监听
     */
    public interface OnNfwxButtonViewListenter {
        void onStartTrackingTouch();

        void onStopTrackingTouch();

        void playEnd();
    }

    /**
     * 设置节目信息
     *
     * @param todayPrograms
     */
    public void setProgramSeek(List<TvProgram> todayPrograms) {
        if (todayPrograms == null) {
            return;
        }
        mTodayPrograms.clear();
        mTodayPrograms.addAll(todayPrograms);
    }

    /**
     * 设置节目信息
     */
    public synchronized void loadProgramSeek() {
        if (mTodayPrograms == null || mTodayPrograms.isEmpty() || mVideoPlayer == null
                || mVideoPlayer.getTimeCode() <= 0 || _hasProgramloaded || !mVideoPlayerController.isLive()) {
            return;
        }
        clearProgramSeek();
        long timecode = 0;
        if (sb_player.getProgress() == sb_player.getMax()) {
            timecode = mVideoPlayer.getTimeCode();
        } else { // 计算出时间
            timecode = mVideoPlayer.getTimeCode() + (sb_player.getMax() - sb_player.getProgress());
        }
        long pretimecode = timecode - live_seek_max;
        List<Point> points = new ArrayList<>();
        for (TvProgram tvProgram : mTodayPrograms) {
            String time = tvProgram.getTime();
            try {
                Date date = dateFormat.parse(time);
                long currentTime = date.getTime() / 1000L;
                int position = (int) ((currentTime - pretimecode) * 100 / live_seek_max);
                if (position >= 0 && position <= 100) {
                    Point point = new Point(position, date.getTime() / 1000L, tvProgram.getProgram_name());
                    points.add(point);
                } else if (position > 100) {
                    break;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        _hasProgramloaded = true;
        sb_player.setPoints(points);
    }

    /**
     * 刷新一次
     */
    public void refreshProgramSeek() {
        _hasProgramloaded = false;
    }

    /**
     * 清除进度节目
     */
    public void clearProgram() {
        mTodayPrograms.clear();
    }

    /**
     * 清除频道信息
     */
    public void clearProgramSeek() {
        if (sb_player != null) {
            sb_player.clearData();
            hiddenBubble();
        }
    }

    /**
     * 清除气泡
     */
    public void hiddenBubble() {
        if (sb_player != null) {
            sb_player.hideBubble();
        }
    }

    private void refreshSeekBar() {
        if (_isSeekEnable) {
            rankBarThumbVisable();
        } else {
            if (mVideoPlayerController.isLive()) {
                rankBarThumbHidden();
            } else {
                rankBarThumbVisable();
            }
        }
    }

    /**
     * 是否支持时间移动
     *
     * @param seekEnable
     */
    public void setSeekEnable(boolean seekEnable) {
        _isSeekEnable = seekEnable;
        refreshSeekBar();
    }

    private void rankBarThumbHidden() {
        Drawable dr = getResources().getDrawable(R.drawable.bg_r2_00ff);
        sb_player.setThumb(dr);
        sb_player.setEnabled(false);
    }

    private void rankBarThumbVisable() {
        Drawable dr = getResources().getDrawable(R.mipmap.player_point_nor);
        sb_player.setThumb(dr);
        sb_player.setEnabled(true);
    }
}
